import { types, Instance, SnapshotOut, SnapshotIn } from "mobx-state-tree"

import { getConfig } from "@/services/api/config"

import { withSetPropAction } from "./helpers/withSetPropAction"

/**
 * Model description here for TypeScript hints.
 */
export const ConfigModel = types
  .model("Config", {
    configs: types.map(types.frozen()), // 动态配置结构
  })
  .actions(withSetPropAction)
  .actions((self) => ({
    updateConfig(updatedInfo: any[]) {
      updatedInfo.forEach((item) => {
        self.configs.set(item.key, item.val)
      })
    },
    getConfigById(key: string) {
      const config = self.configs.get(key)
      if (config) {
        return config
      } else {
        console.warn(`Config with id ${key} not found`)
        return null
      }
    },
  }))
  .actions((self) => ({
    async getSettingConfig() {
      const response: any = await getConfig()
      if (response.data?.code === 200) {
        self.updateConfig(response.data.data.configs)
      } else {
        console.error("Error fetching config", response)
      }
    },
  }))

export interface Config extends Instance<typeof ConfigModel> {}

export interface ConfigSnapshotOut extends SnapshotOut<typeof ConfigModel> {}

export interface ConfigSnapshotIn extends SnapshotIn<typeof ConfigModel> {}

export const createConfigDefaultModel = () =>
  types.optional(ConfigModel, {
    configs: {},
  })
